﻿using System.Linq;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Sunny.Model.RedisCache;
using Sunny.Model.Vo;
using Sunny.Service;
using Sunny.Util.Exception;

namespace Sunny.Api.Filters
{
    
    public class LoginFilter:ActionFilterAttribute
    {
        private readonly RedisService _redisService;

        public LoginFilter(RedisService redisService)
        {
            _redisService = redisService;
        }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var flag = context.ActionDescriptor.EndpointMetadata.Select(t => t.ToString()).Any(t => t.Contains("AllowAnonymous"));
            if(flag)
            {
                base.OnActionExecuting(context);
            }
            else
            {
                var token = context.HttpContext.Request.Headers["token"].ToString();
                if(string.IsNullOrEmpty(token))
                {
                    throw new BusinessException(CodeMessage.TokenInvalid);
                    // context.Result = new JsonResult(Result.Error(CodeMessage.TokenInvalid));
                }
                else
                {
                    var loginUser = _redisService.Get<LoginUser>(UserKeyPrefix.Info, token);
                    if(loginUser == null)
                    {
                        throw new BusinessException(CodeMessage.TokenInvalid);
                        // context.Result = new JsonResult(Result.Error(CodeMessage.TokenInvalid));
                    }
                    else
                    {
                        _redisService.SetEx(UserKeyPrefix.Info, token);
                    }
                }
            }
            
        }
    }
}